package com.example.mapper.dm.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 达梦数据源配置
 */
@Configuration
@Profile("dm")
@MapperScan(basePackages = "com.example.mapper.dm", sqlSessionTemplateRef = "dmSqlSessionTemplate")
public class DmDataSourceConfig {

    @Bean(name = "dmDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.dm")
    public DataSource dmDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dmSqlSessionFactory")
    public SqlSessionFactory dmSqlSessionFactory(@Qualifier("dmDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/dm/**/*.xml"));
        return factoryBean.getObject();
    }

    @Bean(name = "dmTransactionManager")
    public DataSourceTransactionManager dmTransactionManager(@Qualifier("dmDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "dmSqlSessionTemplate")
    public SqlSessionTemplate dmSqlSessionTemplate(@Qualifier("dmSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
} 